package com.nwpu.server.authserver.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.nwpu.server.authserver.dao.UserTokenDao;
import com.nwpu.server.authserver.entity.UserTokenEntity;
import com.nwpu.server.authserver.service.UserTokenService;
import com.nwpu.server.common.constant.CacheConstants;
import com.nwpu.server.common.oauth2.TokenGenerator;
import com.nwpu.server.common.response.PageUtils;
import com.nwpu.server.common.response.Query;
import com.nwpu.server.common.response.R;
import com.nwpu.server.authserver.utils.RedisUtils;
import com.nwpu.server.common.util.TokenUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @Author: YuXingZh
 * @Date: Created in 19:58 2022-04-24
 * @Description:
 */
@Service("userTokenService")
public class UserTokenServiceImpl extends ServiceImpl<UserTokenDao, UserTokenEntity> implements UserTokenService {

    //token过期时间
    @Value("${redis.expireTime}")
    private Long expireTime;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<UserTokenEntity> page = this.page(
                new Query<UserTokenEntity>().getPage(params),
                new QueryWrapper<UserTokenEntity>()
        );

        return new PageUtils(page);
    }

    // token设置12小时后过期
    private final static int EXPIRE = 3600 * 12;

    @Override
    public R createToken(Long userId, String username, String password) {
        //生成一个token
        String token = TokenUtils.token(String.valueOf(userId), username, password);

        //当前时间
        Date now = new Date();
        //过期时间
        Date expireTime = new Date(now.getTime() + EXPIRE);

        //判断是否生成过token
        UserTokenEntity tokenEntity = this.getById(userId);
        if (tokenEntity == null) {
            tokenEntity = new UserTokenEntity();
            tokenEntity.setUserId(userId);
            tokenEntity.setToken(token);
            tokenEntity.setUpdateTime(now);
            tokenEntity.setExpireTime(expireTime);

            //保存token
            this.save(tokenEntity);
        } else {
            tokenEntity.setToken(token);
            tokenEntity.setUpdateTime(now);
            tokenEntity.setExpireTime(expireTime);

            //更新token

            this.updateById(tokenEntity);
        }

        // redis 更新token

        RedisUtils.set(CacheConstants.LOGIN_TOKEN_KEY + token, tokenEntity, EXPIRE, TimeUnit.SECONDS);
        return R.ok().put("token", token).put("expire", EXPIRE).put("info", tokenEntity);
    }


    @Override
    public void logout(long userId) {
        //生成一个token
        String token = TokenGenerator.generateValue();

        //修改token
        UserTokenEntity tokenEntity = new UserTokenEntity();
        tokenEntity.setUserId(userId);
        tokenEntity.setToken(token);
        this.updateById(tokenEntity);
    }
}
